Ext.define("App.datasource.view.SourceTableEditor", {
    extend: 'Extend.window.FormWindow',
    alias: ['widget.SourceTableEditor'],
    requires: ['App.report.model.KpiModel',
        'App.iteration.field.IterationComboBox',
        'App.reportconfiguration.field.ReportConfigurationComboBox',
        'App.datasource.model.SourceDataModel'],
    config: {
        // unmaskable: false,
        entity: 'entity',
        defaults: {
            columnWidth: 1
        },
        window: {
            title: '数据源表编辑',
            width: 950,
            height: 600,
            resizable: false
        }
    },
    items: [{
        xtype: 'hidden',
        name: 'id'
    }, {
        xtype: 'hidden',
        name: 'projectId'
    }, {
        xtype: 'hidden',
        name: 'tableName'
    }, {
        xtype: 'hidden',
        name: 'iterationId'
    }],
    loadRecord: function (record) {
        var me = this;
        var fieldOpts = {
            xtype: 'SourceDataGridField',
            name: 'datas',
            columnWidth: 1,
            height: 500
        };
        if (me.targetGrid.dataTable.type == 'project') {
            // this.down('IterationComboBox').hide();
            // this.down('IterationComboBox').disable();
            fieldOpts.height = 500;
            delete fieldOpts.fieldLabel;
        }
        me.add(Ext.create(fieldOpts));
        // if (Ext.isEmpty(record.get('id'))) {
        //     me.down('IterationComboBox').setReadOnly(false);
        // }
        me.callParent(arguments);
        me.syncFields(record, function (datas) {
            me.down('SourceDataGridField').loadDatas(datas, false);
        })
    },
    syncFields: function (record, callback) {
        var me = this;
        if (Ext.isEmpty(app.project)) {
            return;
        }

        var deleteDatas = function (record, tableFields) {
            var datas = record.get('datas');
            if (!Ext.isEmpty(datas)) {
                for (var i = datas.length - 1; i >= 0; i--) {
                    var data = datas[i];
                    var cfield = data.field;
                    var finded = false;
                    var tableField = Ext.Array.findBy(tableFields, function (item) {
                        if (cfield.id == item.id) {
                            return true;
                        }
                        false;
                    });
                    if (Ext.isEmpty(tableField)) {
                        Ext.Array.remove(datas, data);
                    }
                }
            }
        }

        var addDatas = function (record, tableFields) {
            var datas = record.get('datas');
            if (Ext.isEmpty(datas)) {
                datas = [];
                record.set('datas', datas);
            }
            if (!Ext.isEmpty(tableFields)) {
                for (var i = 0; i < tableFields.length; i++) {
                    var field = tableFields[i];

                    var data = Ext.Array.findBy(datas, function (item) {
                        var cfield = item.field;
                        if (cfield.id == field.id) {
                            return true;
                        }
                        false;
                    });
                    if (Ext.isEmpty(data)) {
                        var data = {field: field, inputValue: "", collectedValue: ''};
                        if (i >= datas.length) {
                            datas.push(data);
                        } else {
                            Ext.Array.insert(datas, i, [data]);
                        }
                    } else {
                        data.field = field;
                        var inputType = Ext.isEmpty(field.collectionField) ? null : field.collectionField.inputType;

                        if (inputType == 1) {
                            data.collectedValue = null;
                        } else if (inputType == 2) {
                            data.inputValue = null;
                        }
                    }
                }
            }
        }
        // me.mask('初始化...');
        Ext.Ajax.request({
            url: 'data_table/query_referenced_data_tables_by_project',
            params: {projectId: app.project.id, tableName: record.get('tableName')},
            success: function (resp) {
                var tableFields = resp.result.data[record.get('tableName')].tableFields;
                if (tableFields != null) {
                    deleteDatas(record, tableFields);
                    addDatas(record, tableFields);
                } else {
                    record.set("datas", []);
                }
                callback(record.get('datas'));
                me.unmask();
            },
            failure: function () {
                me.unmask();
            }
        })
    }
})


Ext.define('App.datasource.view.SourceDataGridField', {
    alias: ['widget.SourceDataGridField'],
    extend: 'Extend.form.field.GridField',
    userCls: 'high-line28',
    submitFields: ['id', 'inputValue', 'collectedValue', 'field.id'],
    roweditable: true,
    tbar: {add: {hidden: true}, remove: {hidden: true}}, border: false,
    model: 'App.datasource.model.SourceDataModel',
    config: {
        selModel: {
            selType: 'rowmodel',
            mode: 'SINGLE'
        }
    },
    columns: [{
        header: '指标名称',
        dataIndex: 'fieldName',
        renderer: function (v, m, r) {
            if (r.get('abandoned') == true) {
                return "<span style='background-color: red;'>" + v + "</span>"
            }
            return v;
        }
    }, {
        header: '录入值',
        dataIndex: 'inputValue', editor: {xtype: 'textfield', itemId: 'inputValue'}
    }, {
        header: '采集值',
        dataIndex: 'collectedValue', editor: {xtype: 'textfield', itemId: 'collectedValue'}
    }],
    listeners: {
        startedit: function (rowedit, e, eOpts) {
            var record = e.record;
            var field = record.get('field');
            var columns = rowedit.grid.columns;

            var inputValueEditor = this.createInputValueEditor(field, columns[1])
            var collectedValueEditor = columns[2].getEditor();
            collectedValueEditor.setReadOnly(true);
            inputValueEditor.setReadOnly(true);
            inputValueEditor.setValue(record.get('inputValue'))

            var inputType = Ext.isEmpty(field.collectionField) ? null : field.collectionField.inputType;
            if (Ext.isEmpty(inputType) || inputType == 1) {
                inputValueEditor.setReadOnly(false);
                collectedValueEditor.setValue();
            } else {
                if (inputType == 2) {
                    inputValueEditor.setReadOnly(true);
                    inputValueEditor.setValue();
                    collectedValueEditor.setReadOnly(true);
                } else {
                    collectedValueEditor.setReadOnly(true);
                    inputValueEditor.setReadOnly(false);
                }
            }
        }
    },
    createInputValueEditor: function (field, column) {
        var inputValueEditor = column.getEditor();
        var dataType = field.dataType;
        if (dataType == 'string') {
            if (!(inputValueEditor.xtypesMap.textfield == true && inputValueEditor.xtypesMap.numberfield != true)) {
                inputValueEditor = Ext.create({
                    xtype: 'textfield',
                    width: inputValueEditor.getWidth()
                });
                column.setEditor(inputValueEditor);
            }
        } else if (dataType == 'int' || dataType == 'float') {
            if (!(inputValueEditor instanceof Ext.form.field.Number)) {
                inputValueEditor = Ext.create({
                    xtype: 'numberfield',
                    width: inputValueEditor.getWidth()
                });
                column.setEditor(inputValueEditor);
            }
            inputValueEditor.decimalPrecision = (dataType == 'int' ? 0 : 4);
        } else if (dataType == 'date') {
            if (!(inputValueEditor instanceof Ext.form.field.Date)) {
                inputValueEditor = Ext.create({
                    xtype: 'datefield',
                    format: 'Y-m-d',
                    editable: false,
                    width: inputValueEditor.getWidth(),
                    getValue: function () {
                        var format = this.submitFormat || this.format,
                            value = this.rawDate;

                        var strdate = value ? Ext.Date.format(value, format) : '';
                        return strdate;
                    }
                });
                column.setEditor(inputValueEditor);
            }
        }
        return inputValueEditor;
    }
})
